package me.jianghs.server;

import me.jianghs.service.MyServerServiceImpl;
import me.jianghs.thrift.StudentService;
import org.apache.thrift.TProcessorFactory;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.server.THsHaServer;
import org.apache.thrift.server.TNonblockingServer;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadedSelectorServer;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TNonblockingServerTransport;
import org.apache.thrift.transport.TTransportException;
import org.apache.thrift.transport.layered.TFramedTransport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class ThriftServer {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    //监听的端口
    @Value("${server.thrift.port}")
    private Integer port;

    //线程池最小线程数
    @Value("${server.thrift.min-thread-pool}")
    private Integer minThreadPool;

    //线程池最大线程数
    @Value("${server.thrift.max-thread-pool}")
    private Integer maxThreadPool;

    //业务服务对象
    @Resource
    MyServerServiceImpl myServerService;

    public void start() {
        try {
            StudentService.Processor<MyServerServiceImpl> processor = new StudentService.Processor<>(myServerService);

            TNonblockingServerTransport transport = new TNonblockingServerSocket(port);

            TThreadedSelectorServer.Args serverArgs = new TThreadedSelectorServer.Args(transport)
                    .selectorThreads(4)
                    .workerThreads(10)
                    .acceptQueueSizePerThread(20)
                    .processor(processor);
            TServer server = new TThreadedSelectorServer(serverArgs);

            logger.info("thrift server started; port:" + port);
            //启动server
            // 异步非阻塞的死循环
            server.serve();
        } catch (TTransportException e) {
            logger.error("server start error", e);
        }
    }

}
